//package com.blinddate.utils;
//
//import com.alibaba.fastjson.JSONObject;
//import okhttp3.HttpUrl;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//
//import javax.crypto.BadPaddingException;
//import javax.crypto.Cipher;
//import javax.crypto.IllegalBlockSizeException;
//import javax.crypto.NoSuchPaddingException;
//import javax.crypto.spec.GCMParameterSpec;
//import javax.crypto.spec.SecretKeySpec;
//import java.io.IOException;
//import java.io.UnsupportedEncodingException;
//import java.security.*;
//import java.security.cert.X509Certificate;
//import java.security.spec.InvalidKeySpecException;
//import java.security.spec.PKCS8EncodedKeySpec;
//import java.util.Base64;
//import java.util.HashMap;
//import java.util.Random;
//
//@Component
//public class SignV3Utils {
//    //V3主商户ID
//    private static String merchantId="1667565626";
//    //微信商户平台APIv3证书序列号
//    private static String certificateSerialNo="4C31889FD6B98EED50962F691569C0AAFA5C3621";
//    //私钥（不要把私钥文件暴露在公共场合，如上传到Github，写在客户端代码等。）
//    private static String privateKey= "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC2apDTO5VeWK9K\n" +
//            "v9WiRIX74jrBx08lbQk1/gHVztDY0g8OQoyF3WLsa3Sv1QMs0vQ2G/2lfH7a6uOu\n" +
//            "/mZ657de1wxlJrSZCwb+q6kwhbtwRCvfMVfsCjYQDlHwXDpeWacNVlhnjDddgKhF\n" +
//            "L80Zq9QyC8YqMYjrrKvgNJ2/je23AKBl7xUc5KwAKzJ3PhieS+uiBK+4IHf88Q43\n" +
//            "KH3dI9PygEiT10YD5fRwBhXC+qZCC9l9J8EouRheb3xHk6YC8aRudRExjBA2tQJg\n" +
//            "VVAr0vEmdfG+jLbioN6fuk6t8yay+dIc5lqbCbsgwTBzujFZITHu+oBorfrvMQWM\n" +
//            "+JenmEjVAgMBAAECggEAS7pryzV2Kge5JdgD0WyPDuV5LQ8X/VqJs19y1ZcZPpnd\n" +
//            "5Daebchdk/Z8J67PtaER/xCZuUS4yRswUGqOksF1b6rpG2j5GnvoeHs9Lsal7NJw\n" +
//            "QCUU8gm/LeU0AQvYs2iWoEPTSZF9PpT1xls0005xNiGLL+MGi4hQhjBxuJ8sK4ck\n" +
//            "ih5txjfb52MR6I6PvhlH7C1MHsUHPHuAlKPvb4lXfRVV9FUiklYgFpwOAnq+YDne\n" +
//            "jSrToKip2HPrY4SInSx9HWo9On+z3BcNqL1rP/fVwkL174CdlY0Nqh1TEwR+aEyB\n" +
//            "ePGb2Xc2rmRjzOLx7WiLouhrAV8NHPcyYThOIHcb4QKBgQDfTK24hTMtA/zTRZnI\n" +
//            "PtVcou+z2djmjqzeVgcLsf0zkZn/7MbCjmKNUnsRRpHf+KqKjYRsd1U6pAdlQ0Kf\n" +
//            "XcRyPiuq/l2R+eA/ozt0YAg6MEhP2a4TR4PJtSC/I3wJTVUM7JPEY7vw5O60enFp\n" +
//            "8Nl0b2I/+6/gCfRpTMnT6iDW/QKBgQDRITTd+W6AF9N3JOp+1HylbvKUnAlQ2X9o\n" +
//            "qdiNEyi+S9VsAbHH+TMsu6DI8Emj8Vzg7l07sA+GgwjqeArxpXU2Ytb8JlHXNHUl\n" +
//            "MzJqxHOnEX8H4KYsPMdoWPPl5YhxXjOgBIMOZp9zyMrVKY5+mDKUBIxZg1bZdAyB\n" +
//            "rMAp9yJcuQKBgQCD2XnmLzhVhzo84ab5FyjSpx7UWnh5QpuOOMu2OyWf0oRVGlEO\n" +
//            "RhapDZ+/RqUR03mXkBI2HYxEsN/xCfMHuM0rC8yrDcDgVeP0j4SmpaGWAjZgd88S\n" +
//            "cTK+4mVwlxpBP9lNZU+nMaCij/rmtDnNbTppRu+DijCCID6iAoZVy7QSXQKBgQCD\n" +
//            "mPnDlOpMALI5DynglaW6FI7hpS7XiYX7PqXeYGgLF309cfOFevMQ+yC6UTqFx6RC\n" +
//            "hrx0it26L0q1AMUiOpP/nULbeOGXIpN0zTq0pNqCDyh4tIzc2YJBz3fq+v1ZGYYy\n" +
//            "86Pks/8yxO+eI4BfeTaaniITUeqc+8HC+AoUXkdpQQKBgQCYGKOzD41VhqP/vRAq\n" +
//            "SzjmbAkUOwKFaY68RfX9EZjRBezJhkCgjRhC32wbeksiGsjD4f64ucgggj1ehB3k\n" +
//            "e55sNAQfEEU+XXU/dtMDEjCCMKlL02wIBtmVVbhS+mG0QWXGs5BZ2QmFzgBqFHfP\n" +
//            "0s7Vhc4KAXpetHKGhAhkjHqpHA==\n";
//
//	//配置文件配置好主商户号
////    @Value("${wechat.v3.merchantId}")
////    public void setMerchantId(String merchantId) {
////        SignV3Utiles.merchantId = merchantId;
////    }
////    //配置文件配置好序列号
////    @Value("${wechat.v3.certificateSerialNo}")
////    public void setCertificateSerialNo(String certificateSerialNo) {
////        SignV3Utiles.certificateSerialNo = certificateSerialNo;
////    }
////	//配置文件配置好私钥
////    @Value("${wechat.v3.privateKey}")
////    public void setPrivateKey(String privateKey) {
////        SignV3Utiles.privateKey = privateKey;
////    }
//    /**
//     * 使用方法
//     * @param method 请求方法
//     * @param url 请求url
//     * @param body 请求内容
//     * @return
//     */
//    public static HashMap<String, String> getSignMap(String method, String url, String body) throws InvalidKeySpecException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, SignatureException {
//        String authorization = getSign(method, url, body);
//
//        HashMap<String, String> headsMap = new HashMap<>();
//        headsMap.put("Authorization", authorization);
//        headsMap.put("Content-Type", "application/json");
//        headsMap.put("Accept", "application/json");
//
//        return headsMap;
//    }
//
//    public static String getSign(String method, String url, String body) throws NoSuchAlgorithmException, SignatureException, InvalidKeySpecException, InvalidKeyException, UnsupportedEncodingException {
//        return "WECHATPAY2-SHA256-RSA2048 " + getToken(method, HttpUrl.parse(url), body);
//    }
//
//    public static String getToken(String method, HttpUrl url, String body) throws UnsupportedEncodingException, SignatureException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
//        String nonceStr = nonceString();
//        long timestamp = System.currentTimeMillis() / 1000;
//        String message = buildMessage(method, url, timestamp, nonceStr, body);
//        String signature = sign(message.getBytes("utf-8"));
//        return "mchid=\"" + merchantId + "\","
//                + "nonce_str=\"" + nonceStr + "\","
//                + "timestamp=\"" + timestamp + "\","
//                + "serial_no=\"" + certificateSerialNo + "\","
//                + "signature=\"" + signature + "\"";
//    }
//
//    public static String sign(byte[] message) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
//        Signature sign = Signature.getInstance("SHA256withRSA");
//        sign.initSign(getPKCS8PrivateKey(privateKey));
//        sign.update(message);
//
//        return Base64.getEncoder().encodeToString(sign.sign());
//    }
//
//    public static String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
////        String canonicalUrl = url.encodedPath();
////        if (url.encodedQuery() != null) {
////            canonicalUrl += "?" + url.encodedQuery();
////        }
//
//        return method + "\n"
//                + "/v3/certificates" + "\n"
//                + timestamp + "\n"
//                + nonceStr + "\n"
//                + body + "\n";
//    }
//
//
//    private static PrivateKey getPKCS8PrivateKey(String strPk) throws NoSuchAlgorithmException, InvalidKeySpecException {
//        String realPK = strPk.replaceAll("-----END PRIVATE KEY-----", "")
//                .replaceAll("-----BEGIN PRIVATE KEY-----", "")
//                .replaceAll("\n", "");
//
//        byte[] b1 = Base64.getDecoder().decode(realPK);
//
//        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b1);
//
//        KeyFactory kf = KeyFactory.getInstance("RSA");
//
//        return kf.generatePrivate(spec);
//    }
//
//    public static String nonceString() {
//
//        String currTime = String.format("%d", (long) System.currentTimeMillis() / 1000);
//
//        String strTime = currTime.substring(8, currTime.length());
//
//        Random random = new Random();
//        int num = (int) (random.nextDouble() * (1000000 - 100000) + 100000);
//        String code = String.format("%06d", num);
//
//        String nonce_str = currTime.substring(2) + code;
//        return nonce_str;
//
//    }
//
//    public static String rsaDecryptOAEP(String ciphertext, PrivateKey privateKey)
//            throws BadPaddingException, IOException {
//        try {
//            Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
//            cipher.init(Cipher.DECRYPT_MODE, privateKey);
//
//            byte[] data = Base64.getDecoder().decode(ciphertext);
//            return new String(cipher.doFinal(data), "utf-8");
//        } catch (NoSuchPaddingException | NoSuchAlgorithmException e) {
//            throw new RuntimeException("当前Java环境不支持RSA v1.5/OAEP", e);
//        } catch (InvalidKeyException e) {
//            throw new IllegalArgumentException("无效的私钥", e);
//        } catch (BadPaddingException | IllegalBlockSizeException e) {
//            throw new BadPaddingException("解密失败");
//        }
//    }
//
//    static final int KEY_LENGTH_BYTE = 32;
//    static final int TAG_LENGTH_BIT = 128;
//
//    private final static String key = "bitworkshopBITWORKSHOP2024022719";
//
//    public static String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
//            throws GeneralSecurityException, IOException {
//        try {
//            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
//            byte[] aesKey = key.getBytes();
//            SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
//            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
//
//            cipher.init(Cipher.DECRYPT_MODE, key, spec);
//            cipher.updateAAD(associatedData);
//
//            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
//        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
//            throw new IllegalStateException(e);
//        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
//            throw new IllegalArgumentException(e);
//        }
//    }
//
//}
//
